﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace XiaoDiCompanion
{
    public partial class MainForm : Form
    {
        private const string MenuName = "小狄伴侣";

        [STAThread]
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            InstallContextMenu();
            if (IsContextMenuInvocation())
            {
                Application.Run(new MainForm());
            }
            //else
            //{
            //    InstallContextMenu();
            //}
        }

        public MainForm()
        {
            InitializeComponent();
            SetupControls();
        }

        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            SuspendLayout();
            // 
            // MainForm
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(300, 150);
            FormBorderStyle = FormBorderStyle.FixedSingle;
            Icon = (Icon)resources.GetObject("$this.Icon");
            MaximizeBox = false;
            MinimizeBox = false;
            Name = "MainForm";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "小狄伴侣";
            FormClosing += MainForm_FormClosing;
            ResumeLayout(false);
        }

        private void SetupControls()
        {
            // 信息标签
            var label = new Label
            {
                Text = "小狄精英",
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleCenter,
                Font = new Font("微软雅黑", 14, FontStyle.Bold)
            };

            // 移除按钮
            var removeBtn = new Button
            {
                Text = "移除右键菜单",
                Dock = DockStyle.Bottom,
                Height = 40,
                Font = new Font("微软雅黑", 9)
            };
            removeBtn.Click += RemoveBtn_Click;

            // 添加控件
            Controls.Add(label);
            Controls.Add(removeBtn);
        }

        private static bool ContextMenuExists()
        {
            using (var key = Registry.ClassesRoot.OpenSubKey(
                $@"*\shell\{MenuName}"))
            {
                return key != null;
            }
        }

        private static void InstallContextMenu()
        {
            if (!IsAdministrator())
            {
                RestartAsAdmin();
                return;
            }

            try
            {
                if (ContextMenuExists())
                {
                    //var result = MessageBox.Show("右键菜单已存在，是否覆盖？",
                    //    "确认操作",
                    //    MessageBoxButtons.YesNo,
                    //    MessageBoxIcon.Question);

                    //if (result != DialogResult.Yes) return;
                    return;
                }

                using (var key = Registry.ClassesRoot.CreateSubKey(
                    $@"*\shell\{MenuName}\command", writable: true))
                {
                    var exePath = Process.GetCurrentProcess().MainModule.FileName;
                    key.SetValue("", $"\"{exePath}\"");
                }
                MessageBox.Show("右键菜单添加成功！", "操作成功",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                Process.GetCurrentProcess().Kill();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加失败：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void RemoveBtn_Click(object sender, EventArgs e)
        {
            Button btn = null;
            if (sender is Button)
            {
                btn = (Button)sender;
                btn.Enabled = false;
            }
            try
            {
                await Task.Run(() => RemoveContextMenu());
                MessageBox.Show("右键菜单已移除！", "操作成功",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"移除失败：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                //if (sender is Button)
                //{
                //var btn = (sender as Button);
                if (btn != null)
                {
                    btn.Enabled = true;
                }
                //}
            }
        }

        private static void RemoveContextMenu()
        {
            if (!IsAdministrator())
            {
                RestartAsAdmin();
                return;
            }

            try
            {
                using (var key = Registry.ClassesRoot.OpenSubKey(@"*\shell", true))
                {
                    key?.DeleteSubKeyTree(MenuName);
                }
            }
            catch
            {
                throw new InvalidOperationException("权限不足或注册表项不存在");
            }
        }

        private static bool IsContextMenuInvocation()
        {
            return Environment.GetCommandLineArgs().Length == 1;
        }

        private static bool IsAdministrator()
        {
            return new WindowsPrincipal(WindowsIdentity.GetCurrent())
                .IsInRole(WindowsBuiltInRole.Administrator);
        }

        private static void RestartAsAdmin()
        {
            var startInfo = new ProcessStartInfo
            {
                FileName = Process.GetCurrentProcess().MainModule.FileName,
                UseShellExecute = true,
                Verb = "runas"
            };

            try
            {
                Process.Start(startInfo);
                Environment.Exit(0);
            }
            catch
            {
                MessageBox.Show("需要管理员权限执行此操作！", "权限不足",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// yzc
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (MessageBox.Show("是否要退出本程序？", "退出程序", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    Process.GetCurrentProcess().Kill();
                }
                else
                {
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Err:{ex.Message}");
            }
        }
    }
}